import config from './config.js'
import store from '../store/index.js'
import wxAuth from './wxAuth.js'

// gptp 域名2
const request = ({url,data={},method='post',toast=true,needLogin=true,headers},gptp) => {
	return new Promise((resolve,reject) => {
		const header = needLogin?{token:store.getters.token}:{};
		const odata = {...header,...data};
		
		uni.request({
			// #ifdef MP-WEIXIN || MP-TOUTIAO || APP
			url: (gptp ? config.proxy1 : config.proxy) + url,
			// #endif
			// #ifdef H5
			url: (gptp ? config.baseUrl1 : config.baseUrl) + url,
			// #endif
			method,
			dataType:'json',
			header: {
				...header,
			},
			data: {
				...data,
			}
		}).then(res => {
			console.log(res.data,'====res.data',)
			console.log('url ===>',url)
			const data = res.data;
			if(res.statusCode === 200) {
				if(data.code === 200) {
					resolve(data.data)
				}
				// 兼容处理腾讯一句话识别回调
				if(data.Result) {
					resolve(data.Result)
				}
			}else {
				if(data.code === 403) {
					console.log(odata,'403')
					// #ifdef H5
					if(import.meta.env.MODE !== 'development') {
						// 重新授权
						wxAuth()
					}
					// #endif
					// #ifdef APP
					uni.redirectTo({
						url: '/pages/login/login'
					})
					reject()
					// #endif
				}else if(data.code === -1) {
					// 需要付费
					store.state.openVip = true;
				}else {
					if(!toast) return;
					uni.showToast({
						icon:'none',
						title: data.message || '服务端错误~'
					})
				}
				reject(data)
				// reject(res)
				// if(!toast) return;
				// uni.showToast({
				// 	icon:'none',
				// 	title:'网络错误~'
				// })
			}
		}).catch(err => {
			console.log(err,'errerere')
			reject(err)
			if(!toast) return;
			uni.showToast({
				icon:'none',
				title: err.message || '未知错误~'
			})
		})
	})
}
const beforeRequest = ({url,data={},method='post',needLogin = true,toast = true,headers},gptp) => {
	console.log('before',store.getters.token)
	if(!getApp().globalData.hasLogin && needLogin) {
		// 需要已登录token，但是未登录或者登录接口未完成时如此处理，将请求挂起
		return new Promise((resolve,reject) => [
			getApp().globalData.requestList.push({
				request:request,
				data:{url,data,method,toast,headers},
				resolve,
				reject,
				gptp
			})
		])
	}else {
		return request({url,data,method,toast,needLogin,headers},gptp)
	}
}
export default beforeRequest